<template>
  <div class="register-page">
    <h2 class="page-title">{{ $t('auth.register.title') }}</h2>
    
    <el-form
      ref="formRef"
      :model="registerForm"
      :rules="rules"
      label-position="top"
      size="large"
    >
      <el-form-item :label="$t('auth.register.email')" prop="email">
        <el-input
          v-model="registerForm.email"
          type="email"
          :placeholder="$t('auth.register.email')"
          prefix-icon="Message"
        />
      </el-form-item>
      
      <el-form-item :label="$t('auth.register.nickname')" prop="nickname">
        <el-input
          v-model="registerForm.nickname"
          :placeholder="$t('auth.register.nickname')"
          prefix-icon="User"
        />
      </el-form-item>
      
      <el-form-item :label="$t('auth.register.password')" prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          :placeholder="$t('auth.register.password')"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      
      <el-form-item :label="$t('auth.register.confirmPassword')" prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          :placeholder="$t('auth.register.confirmPassword')"
          prefix-icon="Lock"
          show-password
        />
      </el-form-item>
      
      <el-form-item prop="agree">
        <el-checkbox v-model="registerForm.agree">
          {{ $t('auth.register.agree') }}
          <el-link type="primary" :underline="false">
            {{ $t('auth.register.terms') }}
          </el-link>
        </el-checkbox>
      </el-form-item>
      
      <el-form-item>
        <el-button
          type="primary"
          size="large"
          style="width: 100%"
          :loading="loading"
          :disabled="isSubmitting"
          @click="handleRegister"
        >
          {{ isSubmitting ? '注册中...' : $t('common.register') }}
        </el-button>
      </el-form-item>
    </el-form>
    
    <div class="auth-switch">
      <span>{{ $t('auth.register.hasAccount') }}</span>
      <router-link to="/auth/login" class="switch-link">
        {{ $t('auth.register.goLogin') }}
      </router-link>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import type { RegisterForm } from '@/types'

const router = useRouter()
const userStore = useUserStore()

// 表单引用
const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const registerForm = reactive<RegisterForm>({
  email: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  agree: false
})

// 表单验证规则
const rules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度为2-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  agree: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请同意用户协议'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 防抖处理
const isSubmitting = ref(false)
let submitTimer: number | null = null

/**
 * 处理注册
 */
const handleRegister = async () => {
  if (!formRef.value || isSubmitting.value) return
  
  // 防止重复提交
  if (submitTimer) {
    clearTimeout(submitTimer)
  }
  
  submitTimer = setTimeout(async () => {
    try {
      const valid = await formRef.value!.validate()
      if (!valid) return
      
      isSubmitting.value = true
      loading.value = true
      const result = await userStore.register(registerForm)
      
      if (result.success) {
        ElMessage({
          message: result.message,
          type: 'success',
          duration: 2000,
          showClose: true
        })
        
        // 延迟跳转到登录页
        setTimeout(() => {
          router.push('/auth/login')
        }, 1000)
      } else {
        ElMessage({
          message: result.message,
          type: 'error',
          duration: 3000,
          showClose: true
        })
      }
    } catch (error) {
      ElMessage({
        message: '注册失败，请重试',
        type: 'error',
        duration: 3000,
        showClose: true
      })
    } finally {
      loading.value = false
      // 延迟重置提交状态
      setTimeout(() => {
        isSubmitting.value = false
      }, 1000)
    }
  }, 300) // 300ms防抖
}
</script>

<style lang="scss" scoped>
.register-page {
  .page-title {
    text-align: center;
    font-size: var(--font-size-2xl);
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: var(--spacing-2xl);
  }
  
  .auth-switch {
    text-align: center;
    margin-top: var(--spacing-lg);
    color: var(--text-secondary);
    
    .switch-link {
      color: var(--primary-color);
      text-decoration: none;
      margin-left: var(--spacing-xs);
      
      &:hover {
        color: var(--primary-dark);
      }
    }
  }
}
</style> 